﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using DesertedRoadStudios.BlogNetNuke.Components;

namespace DesertedRoadStudios.BlogNetNuke.Common
{
    public class TinyURL
    {
        private TinyURLInfo _tinyURL;
        private int _portalID;
        private int _moduleID;

        private const string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        private TinyURL()
        {
        }

        public TinyURL(int portalID, int moduleID)
        {
            _portalID = portalID;
            _moduleID = moduleID;
        }

        public string GenerateURL(out int urlID)
        {
            BlogNetNukeController bnn = new BlogNetNukeController();
            TinyURLInfo urlInfo = bnn.GetTinyUrlDomain(_moduleID);
            urlID = urlInfo.URLID;

            bool authentic = false;
            string code = string.Empty;
            while (!authentic)
            {
                code = string.Empty;
                Random rndm = new Random();
                for (int i = 0; i < 8; i++)
                {
                    code += chars.Substring(rndm.Next(0, chars.Length), 1);
                }

                TinyURLInfo url = bnn.GetPostForTinyUrl(urlInfo.DomainName, code);
                
                if ((url == null) || (!url.Code.Equals(code, StringComparison.InvariantCulture)))
                    authentic = true;
            }

            return code;
        }
    }
}